package com.jdew.thkj.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.nanchen.compresshelper.CompressHelper;
import com.scrat.app.selectorlibrary.ImageSelector;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/4/10 0010.
 */

public class UploadMaterialActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.content)
    EditText content;
    @Bind(R.id.gridView)
    GridView gridView;
    @Bind(R.id.right)
    TextView right;
    @Bind(R.id.zszy)
    CheckBox zszy;
    @Bind(R.id.hdpx)
    CheckBox hdpx;
    @Bind(R.id.xsbk)
    CheckBox xsbk;
    private List<String> imagePaths = new ArrayList<>();
    private static final int REQUEST_CODE_SELECT_IMG = 1;
    private static final int MAX_SELECT_COUNT = 9;
    private int TOTAL_MAX_SELECT_COUNT = 0;
    private GridAdapter gridAdapter;
    private List<File> fileList = new ArrayList<>();
    private List<File> compressFileList = new ArrayList<>();
    private String StyleFrom = "1";
    public Dialog mWeiboDialog;

    @Override
    public int bindLayout() {
        return R.layout.activity_upload_material;
    }

    @Override
    public void initView(View view) {
        back.setVisibility(View.VISIBLE);
        title.setText("发布素材");
        right.setVisibility(View.VISIBLE);
        right.setText("发表");
        back.setOnClickListener(this);
        right.setOnClickListener(this);
        zszy.setOnClickListener(this);
        hdpx.setOnClickListener(this);
        xsbk.setOnClickListener(this);
        imagePaths.add("paizhao");
        gridAdapter = new GridAdapter((ArrayList<String>) imagePaths);
        gridView.setAdapter(gridAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String imgs = (String) parent.getItemAtPosition(position);
                TOTAL_MAX_SELECT_COUNT = MAX_SELECT_COUNT - imagePaths.size() + 1;
                if ("paizhao".equals(imgs)) {
                    ImageSelector.show(UploadMaterialActivity.this, REQUEST_CODE_SELECT_IMG, TOTAL_MAX_SELECT_COUNT);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.right: {
                if (!DeviceUtils.isNetworkAvalible(this)) {
                    ToastUtils.getInstance(this).showMessage("网络连接错误请检查");
                    return;
                }
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                SetUserQrCode();
            }
            break;
            case R.id.zszy: {
                StyleFrom = "1";
                zszy.setChecked(true);
                hdpx.setChecked(false);
                xsbk.setChecked(false);
            }
            break;
            case R.id.hdpx: {
                StyleFrom = "2";
                zszy.setChecked(false);
                hdpx.setChecked(true);
                xsbk.setChecked(false);
            }
            break;
            case R.id.xsbk: {
                StyleFrom = "3";
                zszy.setChecked(false);
                hdpx.setChecked(false);
                xsbk.setChecked(true);
            }
            break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_SELECT_IMG) {
            List<String> list = new ArrayList<>();
            if (null != list) {
                list.clear();
            }
            list.addAll(ImageSelector.getImagePaths(data));
            imagePaths.addAll(list);
            loadAdpater((ArrayList<String>) imagePaths);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void loadAdpater(ArrayList<String> paths) {
        if (imagePaths.contains("paizhao")) {
            imagePaths.remove("paizhao");
        }
        if (imagePaths.size() != 9) {
            imagePaths.add("paizhao");
        }
        gridAdapter = new GridAdapter((ArrayList<String>) imagePaths);
        gridView.setAdapter(gridAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;
        private LayoutInflater inflater;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if (listUrls.size() == 10) {
                listUrls.remove(listUrls.size() - 1);
                loadAdpater(listUrls);
            }
            inflater = LayoutInflater.from(UploadMaterialActivity.this);
        }

        public int getCount() {
            return listUrls.size();
        }

        public void setDataList(List<String> dataList) {
            this.listUrls = (ArrayList<String>) dataList;
            if (listUrls.size() < 9) {
                loadAdpater(listUrls);
            }
            notifyDataSetChanged();
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item, parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.delect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listUrls.remove(position);
                    setDataList(listUrls);
                }
            });
            final String path = listUrls.get(position);
            if (path.equals("paizhao")) {
                holder.image.setImageResource(R.mipmap.find_add_img);
                holder.delect.setVisibility(View.GONE);
            } else {
                holder.delect.setVisibility(View.VISIBLE);
                RequestOptions options = new RequestOptions().centerCrop();
                Glide.with(UploadMaterialActivity.this)
                        .load(path)
                        .apply(options)
                        .into(holder.image);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView image;
            ImageView delect;

            public ViewHolder(View v) {
                image = (ImageView) v.findViewById(R.id.pic);
                delect = (ImageView) v.findViewById(R.id.delect);
            }
        }
    }

    public void SetUserQrCode() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        if(imagePaths.contains("paizhao")){
            imagePaths.remove("paizhao");
        }
        for (int i = 0; i < imagePaths.size(); i++) {
            fileList.add(new File(RegexValidateUtils.getFilePathFromUri(Uri.parse(imagePaths.get(i)))));
            File newFile = new CompressHelper.Builder(this)
                    .setMaxWidth(1920)  // 默认最大宽度为720
                    .setMaxHeight(1080) // 默认最大高度为960
                    .setQuality(80)    // 默认压缩质量为80
                    .setFileName(fileList.get(i).getName()) // 设置你需要修改的文件名
                    .setCompressFormat(Bitmap.CompressFormat.JPEG) // 设置默认压缩为jpg格式
                    .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES).getAbsolutePath())
                    .build()
                    .compressToFile(fileList.get(i));
            compressFileList.add(newFile);
        }
          if(imagePaths.size()<9){
            imagePaths.add("paizhao");
          }
        if (null == fileList || fileList.size()==0) {
            ToastUtils.getInstance(UploadMaterialActivity.this).showMessage("请上传图片");
            return;
        }
        if (TextUtils.isEmpty(content.getText())) {
            ToastUtils.getInstance(UploadMaterialActivity.this).showMessage("请填写此时的想法");
            return;
        }
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        Map<String, RequestBody> uploadMap = new ArrayMap<>();
        uploadMap.put("ContentTitle", RegexValidateUtils.toRequestBody("taolehui"));
        uploadMap.put("ContentText", RegexValidateUtils.toRequestBody(RegexValidateUtils.stringToUnicode(content.getText().toString())));
        uploadMap.put("UserID", RegexValidateUtils.toRequestBody(sp.getString("userId", "")));
        uploadMap.put("StyleFrom", RegexValidateUtils.toRequestBody(StyleFrom));
        List<MultipartBody.Part> uploadFileList = new ArrayList<>();
        for (int i = 0; i < fileList.size(); i++) {
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), compressFileList.get(i));
            MultipartBody.Part body = MultipartBody.Part.createFormData("multipartFiles", compressFileList.get(i).getName(), requestFile);
            uploadFileList.add(body);
        }

        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).ReleaseData(uploadMap, uploadFileList, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "ContentTitle" + RegexValidateUtils.stringToUnicode(content.getText().toString()) + "ContentTexttaolehui" + "UserID" + sp.getString("userId", "") + "StyleFrom" + StyleFrom)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    ToastUtils.getInstance(UploadMaterialActivity.this).showMessage(obj.getString("message"));
                    finish();
                }
            }
        });
    }
}
